<template>
  <a-drawer
    title="绑定业务"
    :visible="visible"
    :destroyOnClose="true"
    :width="600"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-row :gutter="[16, 16]">
      <a-col :span="24" style="padding-left: 33px">
        <a-checkbox v-model:checked="checkAll" @change="onCheckAllChange">
          全选
        </a-checkbox>
      </a-col>

      <a-col :span="24">
        <a-tree
          checkable
          :tree-data="treeData"
          v-model:checkedKeys="checkedKeys"
        >
          <template #title0010
            ><span style="color: #1890ff">sss</span></template
          >
        </a-tree>
      </a-col>
    </a-row>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Form, message, TreeSelect } from "ant-design-vue";
import { QuestionCircleOutlined, UploadOutlined } from "@ant-design/icons-vue";
import utils from "../../../../common/utils/utils";
import request from "../../../../common/utils/request";
import store from "../../../../store/index";

export default defineComponent({
  name: "EditBusiness",
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const state = reactive({
      treeData: [],
      checkedKeys: [],
      resultList: [],
      checkAll: false,
      payMethodList: [],
      methods: [],
    });

    // 关闭弹窗
    const closeModal = () => {
      context.emit("onClose");
    };

    const onSubmit = () => {
      let params = {
        id: props.id,
        business: state.resultList,
      };
      request
        .post("/pay", "/org/pay/config/setBusiness", { ...params })
        .then((res) => {
          message.success("保存成功");
          context.emit("success");
        });
    };

    const getBusinessList = () => {
      request.get("/pay", "/org/pay/config/getBusinessList", {}).then((res) => {
        state.treeData = res.list.map((item) => {
          let obj = {
            title: item.business_name,
            key: `business_${item.id}`,
            value: item.business,
            children: [],
          };
          if (state.methods.length > 0) {
            state.methods.forEach((v) => {
              obj.children.push({
                key: `business_${item.id}_${v.value}`,
                title: v.name,
                value: v.value,
                parentValue: item.business,
              });
            });
          }
          return obj;
        });

        // 回显
        if (
          state.treeData.length > 0 &&
          state.detail.business_info &&
          state.detail.business_info.length > 0
        ) {
          state.treeData.forEach((item) => {
            state.detail.business_info.forEach((businessItem) => {
              if (businessItem.business == item.value) {
                item.children.forEach((childItem) => {
                  if (businessItem.ambient.includes(childItem.value)) {
                    state.checkedKeys.push(childItem.key);
                  }
                });
              }
            });
          });
        }
      });
    };

    const getPayMethodList = () => {
      request.get("/pay", "/org/pay/method_list").then((res) => {
        state.payMethodList = res.payMethodList;
        getConfigDetail();
      });
    };

    const getConfigDetail = () => {
      request
        .get("/pay", "/org/pay/config/detail", { id: props.id })
        .then((res) => {
          state.detail = res.detail;

          let result = [];
          if (state.payMethodList.length > 0) {
            state.payMethodList.forEach((i) => {
              if (i.value == state.detail.pay_method) {
                i.methodList.forEach((j) => {
                  if (j.value == state.detail.pay_sdk) {
                    j.env.forEach((k) => {
                      if (state.detail.pay_env.includes(k.value)) {
                        result.push(k);
                      }
                    });
                  }
                });
              }
            });
          }
          state.methods = result;

          getBusinessList();
        });
    };

    const init = () => {
      getPayMethodList();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          state.checkedKeys = [];
        }
      }
    );

    let emitIdsTimeout = null;
    watch(
      () => state.checkedKeys,
      () => {
        if (emitIdsTimeout) {
          clearTimeout(emitIdsTimeout);
          emitIdsTimeout = null;
        }
        emitIdsTimeout = setTimeout(() => {
          getResultByKeys();
        }, 100);
      }
    );

    const getResultByKeys = () => {
      let result = [];
      state.treeData.forEach((item) => {
        let obj = {
          business: item.value,
          ambient: [],
        };
        item.children.forEach((childItem) => {
          if (state.checkedKeys.includes(childItem.key)) {
            obj.ambient.push(childItem.value);
          }
        });
        result.push(obj);
      });
      state.resultList = result;
    };

    const onCheckAllChange = (e) => {
      let result = [];
      if (e.target.checked) {
        state.treeData.forEach((item) => {
          result.push(item.key);
          item.children.forEach((childItem) => {
            result.push(childItem.key);
          });
        });
      }
      state.checkedKeys = result;
    };

    return {
      ...toRefs(state),
      closeModal,
      onSubmit,
      onCheckAllChange,
    };
  },
});
</script>

<style></style>
